<template>
    <section class="section section-shaped section-lg my-0">
        <div class="shape shape-style-1 bg-gradient-default">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </div>
        <div v-if="showError" class="contentDiv">
            <base-alert type="danger">
                {{errorMsg}}
            </base-alert>
        </div>
        <div v-if="showInfo" class="contentDiv">
            <base-alert class="col-md-6" type="dark">
                {{infoMsg}}
            </base-alert>
        </div>
        <div class="container pt-lg-md">
            <div class="row justify-content-center">
                <div class="col-lg-12">
                    <card v-if="this.dataLoaded" type="secondary" shadow
                          header-classes="bg-white pb-5"
                          body-classes="px-lg-5 py-lg-5"
                          class="border-0 mb-3">
                        <work-order-list v-for="(list,index) in this.results.timeline" :key="index" :msg="list"></work-order-list>
                        <div v-if="this.results.opinionContent" class="row justify-content-center">
                            <div class="col-md-2">
                                <b-img rounded="circle" style="width:100%;height:width" :src="results.timeline[0].icon"></b-img>
                                <h6 style="text-align:center">{{results.timeline[0].name}}</h6>
                            </div>
                            <div class="col-md-10">
                                <base-alert v-if="this.results.opinion === 'good'" type="success">
                                    <span class="alert-inner--icon"><i class="ni ni-bold-up"></i></span>
                                    <span class="alert-inner--text">本次服务评价：<strong>好评</strong></span>
                                </base-alert>
                                <base-alert v-else-if="this.results.opinion === 'medium'" type="info">
                                   本次服务评价：<strong>中评</strong>
                                </base-alert>
                                <base-alert v-else type="warning">
                                    <span class="alert-inner--icon"><i class="ni ni-bold-down"></i></span>
                                    <span class="alert-inner--text">本次服务评价：<strong>差评</strong></span>
                                </base-alert>
                                <strong>评价内容:</strong><br>&nbsp;&nbsp;<strong>{{this.results.opinionContent.text}}</strong><br>
                                <b-img v-for="(rphoto, index) in rphotos" thumbnail v-image-preview style="width:30%" :key="index" :src="rphoto"></b-img>
                            </div>
                        </div>
                    </card>

                    <card v-if="this.results.state === 'unset' || this.results.state === 'set'" type="secondary" shadow
                          header-classes="bg-white pb-5"
                          body-classes="px-lg-5 py-lg-5"
                          class="border-0">
                          <!-- 工单完成之前使用此card -->
                        <div class="row justify-content-center">
                            <textarea v-model="ruleFormA.resMsg" class="form-control form-control-alternative mb-3" rows="3" placeholder="输入处理情况回复"></textarea>
                            <b-form-file
                                multiple
                                accept="image/*"
                                v-model="ruleFormA.photos"
                                :state="ruleFormA.photos.length < 5"
                                placeholder="如有需要传输的图像，拖动至此"
                                drop-placeholder="放下"
                                class="mb-3"
                                browse-text="浏览"
                            ></b-form-file>
                            <b-select v-if="this.role !== 'worker'" class="mb-3" v-model="ruleFormA.selected" :options="ruleFormA.options"></b-select>
                            <base-button @click="submitRes" type="primary">{{submitTextA}}</base-button>
                        </div>
                        <br />
                        <div v-if="this.showErrorA" class="contentDiv">
                            <base-alert type="danger">
                                {{errorMsgA}}
                            </base-alert>
                        </div>
                        <div v-if="this.showInfoA" class="contentDiv">
                            <base-alert class="col-md-6" type="dark">
                                {{infoMsgA}}
                            </base-alert>
                        </div>
                    </card>
                    <card v-if="this.results.state === 'closed' && this.role === 'user'" type="secondary" shadow
                          header-classes="bg-white pb-5"
                          body-classes="px-lg-5 py-lg-5"
                          class="border-0">
                          <!-- 工单完成之后用户使用此card -->
                        <div class="row justify-content-center">
                            <textarea v-model="ruleFormB.judgeMsg" class="form-control form-control-alternative mb-3" rows="3" placeholder="输入对本次服务的评价"></textarea>
                            <b-form-file
                                multiple
                                accept="image/*"
                                v-model="ruleFormB.photos"
                                :state="ruleFormB.photos.length < 5"
                                placeholder="如有需要传输的图像，拖动至此"
                                drop-placeholder="放下"
                                class="mb-3"
                                browse-text="浏览"
                            ></b-form-file>
                            <base-radio name="0" class="mr-3 mb-3" v-model="ruleFormB.radio">好评</base-radio>
                            <base-radio name="1" class="mr-3 mb-3" v-model="ruleFormB.radio">中评</base-radio>
                            <base-radio name="2" class="mr-3 mb-3" v-model="ruleFormB.radio">差评</base-radio>
                        </div>
                        <div class="justify-content-center row">
                            <base-button @click="submitJudge" type="primary">提交</base-button>
                        </div>
                        <div v-if="this.showErrorB" class="contentDiv">
                            <base-alert type="danger">
                                {{errorMsgB}}
                            </base-alert>
                        </div>
                        <div v-if="this.showInfoB" class="contentDiv">
                            <base-alert class="col-md-6" type="dark">
                                {{infoMsgB}}
                            </base-alert>
                        </div>
                    </card>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import WorkOrderList from "./components/workOrderList";
import {
    adminCloseRepair,
    adminReplyRepair,
    checkCookie,
    getRepairDetail,
    getUserInfo,
    mulitUpload, userCloseRepair,
    userReplyRepair, userSubmitJudge,
    workerReplyRepair
} from "../api";
export default {
    components: {WorkOrderList},
    data() {
        return{
            role: 'worker',
            showError: false,
            showInfo: false,
            showErrorA: false,
            showInfoA: false,
            showErrorB: false,
            showInfoB: false,
            errorMsg: '',
            infoMsg: '',
            errorMsgA: '',
            infoMsgA: '',
            errorMsgB: '',
            infoMsgB: '',
            radio: {
                radio1:"radio1"
            },
            file:[],
            paid:true,
            processing:true,
            processed:false,
            isCustomerService:true,
            results: {
                state: 'closed'
            },
            dataLoaded: false,
            loadCount: 0,
            ruleFormA:{
                resMsg: '',
                photos: [],
                selected: null,
                options: [
                    { value: null, text: '若要关闭工单，请选择当前状态为已完成' },
                    { value: '0', text: '已完成' }
                ]
            },
            submitTextA: '提交',
            ruleFormB:{
                judgeMsg: '',
                photos: [],
                radio: "1"
            },
            submitTextB: '提交'
        }
    },
    methods:{
        goPage(page) {
            if (page === -1){
                this.$router.go(-1);
            } else if (page === 0) {
                this.$router.go(0);
            } else {
                this.$router.push({name:page});
            }
        },
        toRealAddr(addr){
            return this.GLOBAL.BASE_URL + addr;
        },
        message(msg){
            this.showError = true;
            this.errorMsg = msg;
        },
        messageA(msg){
            this.showErrorA = true;
            this.errorMsgA = msg;
        },
        messageB(msg){
            this.showErrorB = true;
            this.errorMsgB = msg;
        },
        getWorkOrderDetail(){
            if (!this.$route.params.rid){
                this.$router.push("/work-order-manage");
            } else {
                getRepairDetail({rid: this.$route.params.rid})
                .then(res=>{
                    if (res.code === "1"){
                        this.results = res.data;
                        this.loadCount = this.results.timeline.length;
                        this.results.timeline.forEach(item=>{
                            getUserInfo(item.uid)
                            .then(cres=>{
                                if (cres.code === "1"){
                                    item.icon = cres.data.avatar? this.GLOBAL.BASE_URL + cres.data.avatar: 'img/theme/team-4-800x800.jpg';
                                    item.name = cres.data.name;
                                    item.description = item.text;
                                    this.loadCount--;
                                    if (this.loadCount === 0)
                                    {
                                        this.dataLoaded = true;
                                    }
                                } else {
                                    this.message(cres.data);
                                    return false;
                                }
                            }).catch(err=>{
                                this.message(err);
                                return false;
                            })
                        })
                    } else {
                        this.message(res.msg);
                        return false;
                    }
                }).catch(err=>{
                    this.message(err);
                    return false;
                })
            }
        },
        submitRes(){
            let param = {rid: this.$route.params.rid.toString()};
            this.showErrorA = this.showInfoA = false;
            this.submitTextA = "提交中";
            if (!this.ruleFormA.resMsg){
                this.messageA("回复内容不能为空");
                this.submitTextA = "提交";
                return false;
            } else if (this.ruleFormA.resMsg.length > 500){
                this.messageA("回复内容不能超过500字");
                this.submitTextA = "提交";
                return false;
            } else {
                param.text = this.ruleFormA.resMsg;
            }
            new Promise(resolve => {
                if (this.ruleFormA.photos.length === 0){
                    param.photos = [];
                    resolve();
                } else if (this.ruleFormA.photos.length >= 5) {
                    this.messageA("上传图片不能超过5张");
                    this.submitTextA = '提交';
                    return false;
                } else {
                    let formData = new FormData();
                    this.ruleFormA.photos.forEach(f => {
                        formData.append("files", f);
                    });
                    mulitUpload(formData).then(res=>{
                        if (res.code === "1")
                        {
                            param.photos = res.data;
                            resolve();
                        } else {
                            this.messageA(res.msg);
                            this.submitTextA = '提交';
                            return false;
                        }
                    }).catch(err=>{
                        this.messageA(err);
                        this.submitTextA = '提交';
                        return false;
                    })
                }
            })
            .then(()=>{
                if (this.role === "user"){
                    userReplyRepair(param)
                    .then(res => {
                        if (res.code === "1"){
                            new Promise(resolve => {
                                if (this.ruleFormA.selected === "0"){
                                    userCloseRepair({rid: this.$route.params.rid.toString()})
                                        .then(res=>{
                                            if (res.code === "1"){
                                                resolve();
                                            } else {
                                                this.messageA("提交失败:(");
                                                this.submitTextA = '提交';
                                                return false;
                                            }
                                        }).catch(err=>{
                                        this.messageA(err);
                                        this.submitTextA = '提交';
                                        return false;
                                        })
                                } else {
                                    resolve();
                                }
                            }).then(()=>{
                                this.showInfoA = true;
                                this.infoMsgA = "提交成功！";
                                this.submitTextA = '提交';
                                this.ruleFormA.resMsg = "";
                                setTimeout(() => {this.goPage(0)}, 2000);
                            });
                        } else {
                            this.messageA("提交失败:(");
                            this.submitTextA = '提交';
                            return false;
                        }
                    }).catch(err=>{
                        this.messageA(err);
                        this.submitTextA = '提交';
                        return false;
                    })
                } else if (this.role === "worker"){
                    workerReplyRepair(param)
                    .then(res => {
                        if (res.code === "1"){
                            this.showInfoA = true;
                            this.infoMsgA = "提交成功！";
                            this.submitTextA = '提交';
                            this.ruleFormA.resMsg = "";
                            setTimeout(() => {this.goPage(0)}, 2000);
                        } else {
                            this.messageA("提交失败:(");
                            this.submitTextA = '提交';
                            return false;
                        }
                    }).catch(err=>{
                        this.messageA(err);
                        this.submitTextA = '提交';
                        return false;
                    })
                } else {
                    adminReplyRepair(param)
                    .then(res => {
                        if (res.code === "1"){
                            new Promise(resolve => {
                                if (this.ruleFormA.selected === "0"){
                                    adminCloseRepair({rid: this.$route.params.rid.toString()})
                                        .then(res=>{
                                            if (res.code === "1"){
                                                resolve();
                                            } else {
                                                this.messageA("提交失败:(");
                                                this.submitTextA = '提交';
                                                return false;
                                            }
                                        }).catch(err=>{
                                        this.messageA(err);
                                        this.submitTextA = '提交';
                                        return false;
                                    })
                                } else {
                                    resolve();
                                }
                            }).then(()=>{
                                this.showInfoA = true;
                                this.infoMsgA = "提交成功！";
                                this.submitTextA = '提交';
                                this.ruleFormA.resMsg = "";
                                setTimeout(() => {this.goPage(0)}, 2000);
                            });
                        } else {
                            this.messageA("提交失败:(");
                            this.submitTextA = '提交';
                            return false;
                        }
                    }).catch(err=>{
                        this.messageA(err);
                        this.submitTextA = '提交';
                        return false;
                    })
                }
            }).catch(err=>{
                this.messageA(err);
                this.submitTextA = '提交';
                return false;
            })
        },
        submitJudge(){
            let param = {rid: this.$route.params.rid.toString()};
            this.showErrorB = this.showInfoB = false;
            this.submitTextB = "提交中";
            if (!this.ruleFormB.judgeMsg){
                this.messageB("回复内容不能为空");
                this.submitTextB = "提交";
                return false;
            } else if (this.ruleFormB.judgeMsg.length > 500){
                this.messageB("回复内容不能超过500字");
                this.submitTextB = "提交";
                return false;
            } else {
                param.text = this.ruleFormB.judgeMsg;
            }
            if (this.ruleFormB.radio === "0"){
                param.opinion = 'good';
            } else if (this.ruleFormB.radio === "1"){
                param.opinion = 'medium';
            } else {
                param.opinion = 'bad';
            }
            new Promise(resolve => {
                if (this.ruleFormB.photos.length === 0){
                    param.photos = [];
                    resolve();
                } else if (this.ruleFormB.photos.length >= 5) {
                    this.messageB("上传图片不能超过5张");
                    this.submitTextB = '提交';
                    return false;
                } else {
                    let formData = new FormData();
                    this.ruleFormB.photos.forEach(f => {
                        formData.append("files", f);
                    });
                    mulitUpload(formData).then(res=>{
                        if (res.code === "1")
                        {
                            param.photos = res.data;
                            resolve();
                        } else {
                            this.messageB(res.msg);
                            this.submitTextB = '提交';
                            return false;
                        }
                    }).catch(err=>{
                        this.messageB(err);
                        this.submitTextB = '提交';
                        return false;
                    })
                }
            })
            .then(()=>{
                userSubmitJudge(param)
                    .then(res => {
                        if (res.code === "1"){
                            this.showInfoB = true;
                            this.infoMsgB = "提交成功！";
                            this.submitTextB = '提交';
                            this.ruleFormB.judgeMsg = "";
                            setTimeout(() => {this.goPage(0)}, 2000);
                        } else {
                            this.messageB("提交失败:(");
                            this.submitTextB = '提交';
                            return false;
                        }
                    }).catch(err=>{
                    this.messageB(err);
                    this.submitTextB = '提交';
                    return false;
                })
            }).catch(err=>{
                this.messageB(err);
                this.submitTextB = '提交';
                return false;
            })
        }
    },
    created() {
        checkCookie().then(res=>{
            if (res.code === "1"){
                this.role = res.data;
            } else {
                this.message(res.msg);
                return false;
            }
        }).then(()=>{
            this.getWorkOrderDetail();
        }).catch(err=>{
            this.message(err);
            return false;
        });

        // this.lists.forEach(item => {
        //     item.icon = this.GLOBAL.BASE_URL + item.icon;
        // })
    },
    watch:{
        "$route": "getWorkOrderDetail"
    },
    computed:{
        rphotos(){
            let ret = [];
            if (this.results.opinionContent.photos){
                for(let i = 0; i < this.results.opinionContent.photos.length; i++){
                   ret[i] = this.toRealAddr(this.results.opinionContent.photos[i]);
                }
            }
            return ret;
        }
    }
};
</script>
<style>
.contentDiv{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    margin: auto;
}
select {
      /*Chrome和Firefox里面的边框是不一样的，所以复写了一下*/
      border: solid 1px #000;
      /*很关键：将默认的select选择框样式清除*/
      appearance:none;
      -moz-appearance:none;
      -webkit-appearance:none;
      /*在选择框的最右侧中间显示小箭头图片*/
      background: url("http://ourjs.github.io/static/2015/arrow.png") no-repeat scroll rightright center transparent;
      /*为下拉小箭头留出一点位置，避免被文字覆盖*/
      padding-right: 14px;
    }
    /*清除ie的默认选择框样式清除，隐藏下拉箭头*/
    select::-ms-expand { display: none;
}
</style>
